#include "selector.h"
#include <vector>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>

class SimpleSelector
    : public Selector
{
public:
    SimpleSelector() {}

    virtual void Insert(int fd)
    {
        _fds.emplace_back(fd);
    }
    virtual std::set<int> SelectedKeys()
    {
        int maxfd = 0;
        fd_set fset;
        FD_ZERO(&fset);

        for(auto& fd : _fds) {
            if(fd > maxfd) maxfd = fd;
            FD_SET(fd, &fset);
        }
        timeval timeout = {2, 0};
        int nsel = select(maxfd + 1, &fset, nullptr, nullptr, &timeout);

        std::set<int> nsel_fds;
        ///超时
        if(0 == nsel) {
            goto ret;
        }

        for(auto& fd : _fds) {
            if(FD_ISSET(fd, &fset))
                nsel_fds.insert(fd);
        }

ret:
        FD_ZERO(&fset);

        return nsel_fds;
    }
private:
    std::vector<int> _fds;
};

Selector* SelectorFactory::Create(int type)
{
    Selector* selector = nullptr;

    switch (type)
    {
    case 0:
    {
        selector = new SimpleSelector();
        break;
    }
    default:
        break;
    }

    return selector;
}
